package com.xh.bussiness.permission.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.course.service.IPrepareLessonService;
import com.xh.bussiness.permission.bean.request.BatchSaveOrRemoveUserGroupRequest;
import com.xh.bussiness.permission.bean.request.QueryUserRequest;
import com.xh.bussiness.permission.bean.request.SaveUserSubjectRequest;
import com.xh.bussiness.permission.bean.request.UserRequest;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.model.UserSchool;
import com.xh.bussiness.permission.model.UserSubject;
import com.xh.bussiness.permission.service.IUserSchoolService;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.permission.service.IUserSubjectService;
import com.xh.bussiness.system.bean.request.UserDataPermissionRequest;
import com.xh.bussiness.system.model.GroupUser;
import com.xh.bussiness.system.model.UserDataPermission;
import com.xh.bussiness.system.service.IGroupService;
import com.xh.bussiness.system.service.IGroupUserService;
import com.xh.bussiness.system.service.IUserDataPermissionService;
import com.xh.core.annotation.ExcludeLoginTokenIntercept;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import com.xh.core.util.StringUtils;
import com.xh.core.util.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Api(tags = "用户接口")
@RestController
@RequestMapping("/permission/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IGroupService groupService;
    @Autowired
    private IGroupUserService groupUserService;
    @Autowired
    private IUserSubjectService userSubjectService;
    @Autowired
    private IUserDataPermissionService userDataPermissionService;
    @Autowired
    private IUserSchoolService userSchoolService;
    @Autowired
    private IPrepareLessonService prepareLessonService;

    @ApiOperation(value = "查询用户", notes = "查询用户")
    @RequestMapping("/queryAll")
    @ExcludeLoginTokenIntercept
    public AjaxResult queryAll(UserRequest bean) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", userService.queryUser(bean));
    }

    @ExcludeLoginTokenIntercept
    @ApiOperation(value = "分页查询用户", notes = "分页查询用户")
    @RequestMapping("/queryPage")
    public XhPage queryPage(XhPage page, QueryUserRequest bean) {
        page = userService.queryUserPage(page, bean);
        List<Map<String, Object>> datas =  page.getRecords();
        for (Map<String, Object> data : datas) {
            if(MapUtils.getInteger(data,"resDown") == 1){
                data.put("down",true);
            }else{
                data.put("down",false);
            }
            if(MapUtils.getInteger(data,"resPrint") == 1){
                data.put("print",true);
            }else{
                data.put("print",false);
            }
        }
        return page;
    }

    @ApiOperation(value = "重置用户密码")
    @RequestMapping("/resetPassword")
    public AjaxResult resetPassword(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        String newPassword = userService.resetPassword(userId);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "重置成功", newPassword);
    }


    @ApiOperation(value = "新增用户", notes = "新增用户")
    @PostMapping(value = "/add")
    @Transactional
    public AjaxResult add(@RequestBody UserRequest bean) {
        User exists = userService.getTeacherUserByMobile(bean.getMobile());
        if (exists != null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户手机号已存在");
        }
        if (CollectionUtils.isEmpty(bean.getRoleIds()) || CollectionUtils.isEmpty(bean.getGroupIds())) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        String msg = userService.addUser(bean);
        return new AjaxResult(msg == null, msg);
    }


    @ApiOperation(value = "修改用户", notes = "修改用户")
    @PostMapping(value = "/modify")
    @Transactional
    public AjaxResult modify(@RequestBody UserRequest user) {
        String msg = userService.modifyUser(user);
        return new AjaxResult(msg == null, msg);
    }


    @ApiOperation(value = "删除用户", notes = "删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "String")
    })
    @RequestMapping("/deleteById/{id}")
    @Transactional
    public AjaxResult delete(@PathVariable String id) {
        String msg = userService.deleteUser(id);
        return new AjaxResult(msg == null, msg);
    }


    @ApiOperation(value = "启用/禁用用户", notes = "启用/禁用用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态（0正常，1禁用）", required = true, dataType = "Integer")
    })
    @RequestMapping("/openOrClose")
    public AjaxResult openOrClose(String userId, Integer status) {
        if (StringUtils.isEmpty(userId) || status == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        User user = userService.getById(userId);
        if (user == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户不存在");
        }
        user.setStatus(status);
        userService.update(user);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userId);
    }

    /**
     * 设置用户箐优网学科
     *
     * @param request
     * @return
     */
    @ApiOperation("设置用户箐优网学科")
    @PostMapping("/saveUserSubject")
    public AjaxResult saveUserSubject(@RequestBody SaveUserSubjectRequest request) {
        if (CollectionUtils.isEmpty(request.getUserSubjects())) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        String userId = request.getUserSubjects().get(0).getUserId();
        userSubjectService.deleteByUserId(userId);

        boolean b = userSubjectService.batchInsert(request.getUserSubjects());
        return new AjaxResult(b, b ? "设置成功" : "设置失败");
    }

    /**
     * 根据用户查询箐优网学科
     *
     * @param userId
     * @return
     */
    @ApiOperation("根据用户查询箐优网学科")
    @ApiImplicitParam(name = "userId", value = "用户id")
    @RequestMapping("/queryUserSubjectByUserId")
    public AjaxResult queryUserSubjectByUserId(String userId) {
        List<UserSubject> list = userSubjectService.queryUserJyGradeRange(userId);
        if (CollectionUtils.isEmpty(list)) {
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, new ArrayList<>());
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, list);
    }

    /**
     * 查询用户学段
     *
     * @param userId
     * @return
     */
    @ApiOperation("查询用户学段")
    @ApiImplicitParam(name = "userId", value = "用户id")
    @RequestMapping("/queryUserJyGradeRange")
    public AjaxResult queryUserJyGradeRange(String userId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id", userId);
        qw.groupBy("jy_grade_range");
        List<UserSubject> list = userSubjectService.selectList(qw, UserSubject.class);
        if (CollectionUtils.isEmpty(list)) {
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, new ArrayList<>());
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, list);
    }

    /**
     * 根据用户学段查询学科数据
     *
     * @param userId
     * @param gradeRange
     * @return
     */
    @ApiOperation("根据用户学段查询学科数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id"),
            @ApiImplicitParam(name = "gradeRange", value = "学段"),
    })
    @RequestMapping("/queryUserJySubjectByRange")
    public AjaxResult queryUserJySubjectByRange(String userId, String gradeRange) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id", userId);
        qw.eq("jy_grade_range", gradeRange);
        List list = userSubjectService.selectList(qw, UserSubject.class);
        if (CollectionUtils.isEmpty(list)) {
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, new ArrayList<>());
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, list);
    }

    /**
     * 查询用户组
     *
     * @param userId
     * @return
     */
    @RequestMapping("/queryUserGroupByUserId")
    public AjaxResult queryUserGroupByUserId(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, groupService.queryUserGroupByUserId(userId));
    }
    /**
     * 查询当前用户的学科组
     * @author 赵文博
     * @date 2021/6/22 10:35
     * @return com.xh.core.bean.AjaxResult
     **/
    @GetMapping("/queryGroupByUserId")
    public AjaxResult queryGroupByUserId(){
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, groupService.queryGroupByUserId(UserUtils.getCurrentUserId()));
    }

    /**
     * 查询用户所属校区
     *
     * @param userId
     * @return
     */
    @RequestMapping("/querySchoolByUserId")
    public AjaxResult querySchoolByUserId(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userSchoolService.querySchoolByUserId(userId));
    }

    /**
     * 通过用户id查询数据
     *
     * @param userId
     * @return
     */
    @RequestMapping("/queryUserDetailById")
    public AjaxResult queryUserDetailById(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userService.queryUserDetailById(userId));
    }


    @ApiOperation(value = "将用户移出分组", notes = "将用户移出分组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "groupId", value = "分组id", required = true, dataType = "String")
    })
    @RequestMapping("/removeUserGroup")
    @Transactional
    public AjaxResult removeUserGroup(String userId, String groupId) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(groupId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(groupUserService.deleteByUserId(userId, groupId));
    }

    @ApiOperation(value = "将用户添加到分组", notes = "将用户添加到分组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "groupId", value = "分id", required = true, dataType = "String")
    })
    @RequestMapping("/addUserGroup")
    @Transactional
    public AjaxResult addUserGroup(String userId, String groupId) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(groupId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        GroupUser groupUser = groupUserService.queryGroupUerByUserIdAndGroupId(userId, groupId);
        if (groupUser != null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "该用户已在组内");
        }
        groupUser = new GroupUser();
        groupUser.setGroupId(groupId);
        groupUser.setUserId(userId);

        return new AjaxResult(groupUserService.insert(groupUser));
    }

    @ApiOperation(value = "查询用户数据权限", notes = "查询用户数据权限")
    @RequestMapping("/queryUserDataPermission")
    public AjaxResult queryUserDataPermission(String userId) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userService.queryUserDataPermission(userId));
    }

    @ApiOperation(value = "保存用户数据权限", notes = "保存用户数据权限")
    @RequestMapping("/saveUserDataPermission")
    public AjaxResult saveUserDataPermission(@RequestBody UserDataPermissionRequest request) {
        return new AjaxResult(userDataPermissionService.saveUserDataPermission(request));
    }

    @ApiOperation(value = "用户数据学科", notes = "用户数据学科")
    @RequestMapping("/userDataSubjects")
    public AjaxResult userDataSubjects(HttpServletRequest request) {
        String userId = request.getHeader("userId");
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userService.userDataSubjects(userId));
    }

    @ApiOperation(value = "用户数据权限", notes = "用户数据权限")
    @RequestMapping("/userDataRules")
    public AjaxResult userDataRules(String userId, String subjectCode) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userService.userDataRules(userId, subjectCode));
    }

    /**
     * 批量添加或移除分组
     *
     * @return
     */
    @RequestMapping("/batchSaveOrRemoveUserGroup")
    public AjaxResult batchSaveOrRemoveUserGroup(@RequestBody BatchSaveOrRemoveUserGroupRequest removeUserGroupRequest) {
        List<String> groupIds = removeUserGroupRequest.getGroupIds();
        if (CollectionUtils.isEmpty(groupIds)) {
            // 删除所有的组数据
            groupUserService.deleteByUserId(removeUserGroupRequest.getUserId(), null);

            // 分组为空的情况，清空用户个人所有权限
            QueryWrapper<UserDataPermission> qw = new QueryWrapper<>();
            qw.eq("user_id", removeUserGroupRequest.getUserId());
            userDataPermissionService.deleteByCondition(qw);
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
        }

        List<GroupUser> groupUsers = groupUserService.queryGroupUserByUserId(removeUserGroupRequest.getUserId());
        if (!CollectionUtils.isEmpty(groupUsers)) {
            for (GroupUser groupUser : groupUsers) {
                // 新的组id集合中不包含该组id，删除，否则groupIds除去该id，
                if (!groupIds.contains(groupUser.getGroupId())) {
                    // 这里其实少了一步，应该组对应的数据权限, 情况比较复杂，暂时先不清
                    groupUserService.deleteByUserId(removeUserGroupRequest.getUserId(), groupUser.getGroupId());
                } else {
                    groupIds.remove(groupUser.getGroupId());
                }
            }
        }
        // 剩下的组id为新增用户组
        if (!CollectionUtils.isEmpty(groupIds)) {
            for (String groupId : removeUserGroupRequest.getGroupIds()) {
                GroupUser groupUser = new GroupUser();
                groupUser.setGroupId(groupId);
                groupUser.setUserId(removeUserGroupRequest.getUserId());
                groupUserService.insert(groupUser);
            }
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    @RequestMapping("/queryUserList")
    public AjaxResult queryUserList(String subjectCode, String schoolId, String groupId) {
        //根据校区或分组查询用户，没传参数默认按当前用户所属校区分组进行查询
        QueryUserRequest userRequest = new QueryUserRequest();
        if (StringUtils.isEmpty(schoolId)) {
            List<UserSchool> schools = userSchoolService.queryUserSchoolByUserId(UserUtils.getCurrentUserId());
            if (!CollectionUtils.isEmpty(schools)) {
                userRequest.setSchoolIds(schools.stream().map(item -> item.getSchoolId()).collect(Collectors.toList()));
            }
        } else {
            userRequest.setSchoolId(schoolId);
        }
        if (StringUtils.isEmpty(groupId)) {
            if (StringUtils.isEmpty(schoolId) && CollectionUtils.isEmpty(userRequest.getSchoolIds())) {
                List<GroupUser> groupUsers = groupUserService.queryGroupUserByUserId(UserUtils.getCurrentUserId());
                if (!CollectionUtils.isEmpty(groupUsers)) {
                    userRequest.setGroupIds(groupUsers.stream().map(item -> item.getUserId()).collect(Collectors.toList()));
                }
            }
        } else {
            userRequest.setGroupId(groupId);
        }
        List<User> users = userService.queryUserList(userRequest);
        if (!CollectionUtils.isEmpty(users)) {
            users.forEach(item -> {
                item.setPrepareLessonAvgScore(prepareLessonService.queryUserPrepareLessonAvgScore(subjectCode, item.getId()));
            });
        }
        List<User> resultList = users.stream().sorted(Comparator.comparing(User::getPrepareLessonAvgScore)).collect(Collectors.toList());
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, resultList);
    }

    @ApiOperation(value = "用户数据权限", notes = "用户数据权限")
    @RequestMapping("/updateUserResPermission")
    public AjaxResult updateUserResPerssion(String  userId, String resPermission, Integer value) {
        User user = userService.getById(userId);
        if("down".equals(resPermission)){
            user.setResDown(value);
            userService.update(user);
        }else if("print".equals(resPermission)){
            user.setResPrint(value);
            userService.update(user);
        }else{
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误：resPermission");
        }

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "修改成功！");
    }
}
